/**
 * 管理系统-分类目录-接口路由模块
 */
const express = require('express')
const router = express.Router()

/**
 * 引入其他模块
 */
const db = require('../../utils/db')

// 获取所有分类
router.get('/api/categories', (req, res, next) => {
  const sql = 'select * from ali_cate'
  db.query(sql, (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true,
      categoriesList: result
    })
  })
})
// 添加分类
router.post('/api/categories/add', (req, res, next) => {
  const sql = 'insert into ali_cate (cate_name, cate_slug) values (?, ?)'
  db.query(sql, [req.body.cate_name, req.body.cate_slug], (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})
// 显示编辑
router.post('/api/categories/editShow', (req, res, next) => {
  const sql = 'select * from ali_cate where cate_id = ?'
  db.query(sql, req.body.id, (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true,
      data: result[0]
    })
  })
})
// 编辑分类
router.post('/api/categories/edit', (req, res, next) => {
  const sql = 'update ali_cate set cate_name = ?, cate_slug = ? where cate_id = ?'
  const {cate_name, cate_slug, cate_id} = req.body
  console.log('req.body---', req.body)
  db.query(sql, [cate_name, cate_slug, cate_id], (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})
// 删除分类
router.post('/api/categories/delete', (req, res, next) => {
  const sql = 'delete from ali_cate where cate_id = ?'
  db.query(sql, req.body.id, (err, result) => {
    if (err) return next(err)
    res.status(200).json({
      success: true
    })
  })
})

module.exports = router